package nl.rainbowsheep.reisorg.rest.service.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.rainbowsheep.reisorg.rest.service.model.City;
import nl.rainbowsheep.reisorg.rest.service.model.CityLocalized;
import nl.rainbowsheep.reisorg.rest.service.model.Country;
import nl.rainbowsheep.reisorg.rest.service.model.Language;
import nl.rainbowsheep.reisorg.rest.service.model.Region;
import nl.rainbowsheep.reisorg.rest.service.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Service for City
 */
@Service
public class CityService {

    @Autowired
    private CityRepository cityRepository;

    @Autowired
    private CountryService countryService;

    @Autowired
    private RegionService regionService;

    public City findById(long id) {
        City c = cityRepository.findOne(id);
        return c;
    }

    public List<City> getAllCities() {
        List<City> cities = cityRepository.findAll();
        return cities;
    }

    public City getCityByName(String name) {
        City city = cityRepository.findByName(name);
        return city;
    }

    public List<City> getAllCitiesByCountry(String country) {
        Country searchedCountry = countryService.getCountryByName(country);
        List<City> cities = cityRepository.findByCountryId(searchedCountry.getId());
        return cities;
    }

    public List<City> getAllCitiesByCountryId(Long id) {
        List<City> cities = cityRepository.findByCountryId(id);
        return cities;
    }

    public List<City> getAllCitiesByRegionId(Long id) {
        List<City> cities = cityRepository.findByRegionId(id);
        return cities;
    }

    
    public List<City> getAllCitiesByRegion(String region) {
        Region searchedRegion = regionService.getRegionByName(region);
        List<City> cities = cityRepository.findByRegionId(searchedRegion.getId());
        return cities;
    }

    public City save(City city) {
        City cityToCheck = getCityByName(city.getName());
        Map<Language, CityLocalized> localizedMap = null;

        if (cityToCheck != null) {
            city.setId(cityToCheck.getId());
            if (cityToCheck.getLocale() != null) {
                localizedMap = cityToCheck.getLocale();
            }
        }
        if (localizedMap == null) {
            localizedMap = new HashMap<Language, CityLocalized>();
        }
        city.setLocale(localizedMap);
        Date currentDate = new Date();
        city.setLastUpdate(new Timestamp(currentDate.getTime()));
        return cityRepository.save(city);
    }

}
